package com.loveyukari.service;

import com.loveyukari.dao.AddressDao;
import com.loveyukari.model.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AddressService {

    @Autowired
    private AddressDao addressDao;
    @Autowired
    private RedisService redisService;


    public List<Address> getAuthAddress(Integer authId){
        if (authId == null){
            return new ArrayList<>();
        }
        List<Address> list = addressDao.selectByAuth(authId);
        return list;
    }

    private String addressKey = "address:";
    public Address getCacheAddress(Integer id){
        String key = addressKey+id;
        Address address = redisService.get(key, Address.class);
        if (address == null){
            address = addressDao.select(id);
            if (address == null){
                return null;
            }
            redisService.set(key,address);
        }
        return address;
    }

    public void addAuthAddress(String address, String name, String phone, Integer authId){
        Address authAddress = new Address();
        authAddress.setPhone(phone);
        authAddress.setName(name);
        authAddress.setAddress(address);
        authAddress.setAuthId(authId);
        addressDao.insert(authAddress);
    }

    public void deleteAuthAddress(Integer id,Integer authId){
        Address address = addressDao.select(id);
        if (address == null){
            return;
        }
        if (address.getAuthId().equals(authId)){
            addressDao.updateStatus(id,-1);
        }
    }


}
